﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using DotNetNuke.Entities.Content;
using System.Linq;

namespace Dynamo
{
    public partial class DynamoViewer : DNNXHR.XHRPortalModule, DotNetNuke.Entities.Modules.IActionable
    {
        DotNetNuke.Entities.Modules.ModuleController controller = new DotNetNuke.Entities.Modules.ModuleController();
        DNNJintEngine engine;

        protected override void OnInit(EventArgs e)
        {
            base.ClientMethods.Add("ServerEcho", new XHRCall(Echo));
            
            base.OnInit(e);
        }
        private string Echo(string p) { return p; }
        protected void Page_Load(object sender, EventArgs e)
        {
            UpdatePanel2.Visible = Dynamo.AdminPermissions.ScriptingEnabled;
            DisabledPanel.Visible = !Dynamo.AdminPermissions.ScriptingEnabled;
            EditScriptHyperLink.Visible = false;

            if (Dynamo.AdminPermissions.ScriptingEnabled)
            {
                if (base.UserInfo.IsSuperUser)
                {
                    EditScriptHyperLink.Visible = true;
                    EditScriptHyperLink.NavigateUrl = EditUrl("Edit");
                }
                engine = new DNNJintEngine(Panel1, this.Page, this);
                engine.Debug = (System.Web.HttpContext.Current.IsDebuggingEnabled || this.UserInfo.IsSuperUser);
                
                string script = Dynamo.AdminPermissions.LoadScript(TabId, ModuleId);
                if (string.IsNullOrEmpty(script)) script = "@{return \"Hello World\";}@";
                string result = engine.Run(script);
                if (result != null) this.Panel1.Controls.Add(new LiteralControl(result));
            }
        }

        public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection actions = new ModuleActionCollection();
                actions.Add(GetNextActionID(), "Edit Script", "Edit", "", "", EditUrl("Edit"), false, SecurityAccessLevel.Edit, true, false);
                actions.Add(GetNextActionID(), "Portal Script Settings", "Settings", "", "", EditUrl("Settings"), false, SecurityAccessLevel.Host, true, false);
                return actions;
            }
        }

    }
}